/**
 * Created by kevin on 2017/6/2.
 */
var express = require('express');
var Users = require('../models/Users');
var router = express.Router();
var url = require("url");
var Robots = require('../models/Robots');
var Applications = require('../models/Applications');
var Packages = require('../models/Packages');
var ucheck = require('../utils/ucheck');
var multer  = require('multer');
var Delegater = require('../models/Delegaters');
var events = require('events');
var GitUsers = require('../models/GitUsers');

var upload = multer({dest:'data/uploads/'});

router.post('/get',function (req,res,next) {
    ucheck.hasLogin(res,function (has) {
        if (!has) {
            req.flash('error', '请先登录');
            return res.redirect('/user/login?redirect='+req.originalUrl);
        }
        ucheck.AIPackager(res,function (is) {
            if (!is) {
                return res.json({
                    message : '您无权查看',
                    code : -1,
                    data : null
                });
            }
            var id = req.body['id'];
            Applications.getById(id,function (err,app) {
                if (err) {
                    res.json({
                        message : err.message,
                        code : -1,
                        data : null
                    });
                } else  {
                    res.json({
                        message : '成功',
                        code : 0,
                        data : app
                    });
                }
            });
        });
    });


});

router.get('/*',function (req,res,next) {
    ucheck.hasLogin(res,function (has) {
        if (!has) {
            req.flash('error', '请先登录');
            return res.redirect('/user/login?redirect='+req.originalUrl);
        }
        ucheck.AIManager(res,function (is) {
            if (!is) {
                req.flash('error', '您无权查看');
                return res.redirect('/');
            }
            next();
        });
    });
});

router.post('/*',function (req,res,next) {
    ucheck.hasLogin(res,function (has) {
        if (!has) {
            return res.json({
                message : '请先登录',
                code : -1,
                data : null
            });
        }
        ucheck.AIManager(res,function (is) {
            if (!is) {
                return res.json({
                    message : '您无权查看',
                    code : -1,
                    data : null
                });
            }
            next();
        });
    });
});

router.get('/', function(req, res, next) {
    let platform = req.query.platform;
    if (platform && platform.length > 0) {
        platform = platform.toLowerCase();
    } else  {
        platform = 'ios';
    }

    let isNew = req.query.new;
    if (isNew) {
        isNew = 1;
    } else  {
        isNew = 0;
    }
    if (platform === 'android' && ucheck.canManagerAndroidSync(res)) {
        // 安卓
        req.session.addType = 2;
        Robots.getAll(function (err,robots) {
            GitUsers.getAll(function (e,g) {
                res.render('app/list',{title:'Android应用管理',type:2,platform:'Android',robots:robots,isNew:isNew,gitusers:g});
            });
        });

    } else if (platform === 'ios' && ucheck.canManagerIOSSync(res)) {
        // ios
        req.session.addType = 1;
        Robots.getAll(function (err,robots) {
            GitUsers.getAll(function (e,g) {
                res.render('app/list',{title:'iOS应用管理',type:1,platform:'iOS',robots:robots,isNew:isNew,gitusers:g});
            });
        });
    } else if (platform !== 'android' && platform !== 'ios') {
        // 非法
        req.flash('error', '平台信息有误，请核实');
        res.redirect('/');
    } else {
        req.flash('error', '您无权查看');
        res.redirect('/');
    }
});

router.post('/list',function (req,res,next) {
    Applications.getListByType(req.session.addType,function (err,apps) {
        if (err) {
            res.json({
                message : err.message,
                code : -1,
                data : null
            });
        } else  {
            res.json({
                message : '成功',
                code : 0,
                data : apps
            });
        }
    });
});

router.post('/add', upload.single('icon'),function (req,res,next) {
    var file = req.file;
    if (!file) {
        return res.json({
            message : '应用图标不能为空',
            code : -1,
            data : null
        });
    } else {
        if (file.mimetype.indexOf('png') < 0 && file.mimetype.indexOf('jpg') < 0 && file.mimetype.indexOf('jpeg') < 0) {
            return res.json({
                message : '应用图标类型不正确',
                code : -1,
                data : null
            });
        }
    }
    var name = req.body['name'];
    var version = req.body['version'];
    var bundleId = req.body['bundleId'];
    var branch = req.body['branch'];
    var sign = req.body['sign'];
    var project = req.body['project'];
    var url = req.body['url'];
    var config = req.body['configuration'];
    var gitUser = req.body['gituser'];
    var teamId = req.body['teamid'];
    var robots = JSON.parse(req.body['robots']);

    var status = req.body['status'];
    var type = req.session.addType;

    console.log(robots + typeof(robots));

    var emptyInfo = ['名称','版本','标识','Git分支','Git地址','工程名'];
    var emptyCheck = [name,version,bundleId,branch,url,project];
    var eventEmitter = new events.EventEmitter();
    var needBreak = false;
    emptyCheck.forEach(function (item,index) {
        if (needBreak) return;
        if (!item) {
            return res.json({
                message : emptyInfo[index] + '不能为空',
                code : -1,
                data : null
            });
        }
        if (index === emptyCheck.length - 1) {
            console.log('check_finish1');
            process.nextTick(function () {
                eventEmitter.emit('check_finish');
                console.log('check_finish');
            });
        };
    });

    eventEmitter.once('check_finish',function () {
        if (!sign && type === 1) {
            return res.json({
                message : '签名证书不能为空',
                code : -1,
                data : null
            });
        }
        var app = ({
            name : name,
            bundleId : bundleId,
            version : version,
            iconUrl : '/' + file.path,
            type : type,
            gitlab : url,
            branch : branch,
            teamId : teamId,
            projectName : project,
            sign : sign,
            status : status,
            configuration : config,
            gitUser : gitUser,
            robots : robots
        });
        Applications.createUniqueName(app,function (err,aApp) {
            if (err) {
                res.json({
                    message : err.message,
                    code : -1,
                    data : null
                });
            } else  {
                res.json({
                    message : '成功',
                    code : 0,
                    data : null
                });
            }
        });
    });

});

router.post('/del',function (req,res,next) {
    let id = req.body['id'];
    Applications.remove({'_id':id},function (err) {
        if (err) {
            res.json({
                message : err.message,
                code : -1,
                data : null
            });
        } else {
            res.json({
                message : '成功',
                code : 0,
                data : null
            });
        }
    });
});

router.post('/edit', upload.single('icon'),function (req,res,next) {
    var file = req.file;
    var name = req.body['name'];
    var version = req.body['version'];
    var bundleId = req.body['bundleId'];
    var branch = req.body['branch'];
    var config = req.body['configuration'];
    var sign = req.body['sign'];
    var project = req.body['project'];
    var url = req.body['url'];
    var gitUser = req.body['gituser'];
    var gitPath = req.body['gitPath'];
    var teamId = req.body['teamid'];
    var robots = JSON.parse(req.body['robots']);
    var id = req.body['id'];

    var status = req.body['status'];
    var type = req.session.addType;

    var emptyInfo = ['名称','版本','标识','Git分支','Git地址','工程名'];
    var emptyCheck = [name,version,bundleId,branch,url,project];
    var eventEmitter = new events.EventEmitter();
    var needBreak = false;
    emptyCheck.forEach(function (item,index) {
        if (needBreak) return;
        if (!item) {
            needBreak = true;
            return res.json({
                message : emptyInfo[index] + '不能为空',
                code : -1,
                data : null
            });
        }
        if (index === emptyCheck.length - 1) {
            process.nextTick(function () {
                eventEmitter.emit('check_finish');
            });
        };
    });
    eventEmitter.once('check_finish',function () {
        if (!sign && type === 1) {
            return res.json({
                message : '签名证书不能为空',
                code : -1,
                data : null
            });
        }
        var app = ({
            name : name,
            bundleId : bundleId,
            version : version,
            type : type,
            gitlab : url,
            branch : branch,
            projectName : project,
            gitPath : gitPath,
            sign : sign,
            status : status,
            configuration : config,
            gitUser : gitUser,
            teamId : teamId,
            robots : robots
        });
        console.log(JSON.stringify(app));
        if (file && file.path) {
            app.iconUrl = '/'+file.path;
        }

        Applications.edit(id,app,function (err,aApp) {
            if (err) {
                res.json({
                    message : err.message,
                    code : -1,
                    data : null
                });
            } else  {
                res.json({
                    message : '成功',
                    code : 0,
                    data : null
                });
            }
        });
    });

});

module.exports = router;
